<template>
  <div class="self-page">
    <div class="self-component">
      <h1>组件</h1>
      <div class="scroll">
        <draggable
          :list="componentsList"
          :move="onMoveCallback"
          :sort="false"
          :group="{ name: 'component', pull: 'clone', put: false }"
        >
          <div v-for="(component, index) in componentsList" :key="index" class="s-row">
            <i :class="component.icon"></i>
            <span>{{ component.name }}</span>
          </div>
        </draggable>
      </div>
    </div>
    <div class="self-content">
      <ul class="header">
        <li :class="{ active: currentNavigator === 'pc' }" @click="handleNavigatorChange('pc')">
          <i class="el-icon-monitor"></i>
          <span>PC</span>
        </li>
        <li
          :class="{ active: currentNavigator === 'mobile' }"
          @click="handleNavigatorChange('mobile')"
        >
          <i class="el-icon-mobile-phone"></i>
          <span>手机端</span>
        </li>
        <li :class="{ active: currentNavigator === 'ipad' }" @click="handleNavigatorChange('ipad')">
          <i class="el-icon-mobile-phone rotate"></i>
          <span>平板端</span>
        </li>
        <li class="fr">
          <span @click="handleSave">
            <i class="el-icon-check"></i>
            <em>保存</em>
          </span>
          <span @click="handleBack">
            <i class="el-icon-close"></i>
            <em>取消</em>
          </span>
        </li>
      </ul>
      <div class="self-in">
        <draggable
          ref="dragArea"
          v-model="renderedComponents"
          v-bind="dragOptions"
          group="component"
          class="drag-area"
          :class="{ isIpad: currentNavigator === 'ipad', isMobile: currentNavigator === 'mobile' }"
          @change="onChange"
        >
          <div
            v-for="(component, index) in renderedComponents"
            :key="index"
            :class="{ active: currentIndex === index }"
            @click="handleSelect(component, index)"
          >
            <component
              :is="component.component"
              :componentData="component.componentData"
              :navigator="currentNavigator"
            />
            <span class="operation" @click="handleDelete">
              <i class="el-icon-delete"></i>
            </span>
          </div>
        </draggable>
      </div>
    </div>
    <div class="self-detail">
      <h1>组件设置</h1>
      <div v-if="selectedComponent.component" class="scroll">
        <component
          :is="`${selectedComponent.component}-detail`"
          :componentData="selectedComponent.componentData"
          @change="itemChange"
        />
      </div>
    </div>
    <common-dialog-form
      ref="commonForm"
      size="small"
      :visible.sync="visible"
      :title="drawerTitle"
      :content="formContent"
      :onConfirm="onConfirm"
    ></common-dialog-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import _clonedeep from 'lodash.clonedeep'
import draggable from 'vuedraggable'

import CommonDialogForm from '@/components/common-dialog-form'
import Panles from '@/container/configure/self-page/component/importComponents.js'
import DetailPanles from '@/container/configure/self-page/detail/importComponents.js'

import { configureSelfPage } from '@/const/path'
import * as api from '@/const/api'

export default {
  title: '新增自定义页面',
  name: 'ConfigureSelfPageEdit',
  components: {
    draggable,
    CommonDialogForm,
    ...Panles,
    ...DetailPanles,
  },
  inject: ['reload'],
  data() {
    return {
      currentNavigator: 'pc',
      currentRow: {},
      componentsList: [
        {
          icon: 'el-icon-picture',
          name: 'banner图',
          component: 'banner-item',
          componentData: {
            coverImage: '',
            coverImageApp: '',
            titleZh: '',
            titleEn: '',
          },
        },
        {
          icon: 'el-icon-picture',
          name: '多语言图片',
          component: 'mult-picture',
          componentData: {
            type: '1',
            pdfZh: '',
            pdfEn: '',
            pcImgZh: '',
            pcImgEn: '',
            h5ImgZh: '',
            h5ImgEn: '',
            titleZh: '',
            titleEn: '',
            subtitleZh: '',
            subtitleEn: '',
            descZh: '',
            descEn: '',
          },
        },
        {
          icon: 'el-icon-s-data',
          name: '图标切换组件',
          component: 'tab-box',
          componentData: {
            list: [],
            defaultColor: '#eef6fe',
            activeColor: '#0261bc',
          },
        },
        {
          icon: 'el-icon-s-data',
          name: '中英标题',
          component: 'title-item',
          componentData: {
            titleZh: '',
            titleEn: '',
          },
        },
        {
          icon: 'el-icon-s-data',
          name: '图文左右排列',
          component: 'graphic-layout',
          componentData: {
            titleZh: '',
            titleEn: '',
            contentZh: '',
            contentEn: '',
            coverImage: '',
            imgAlign: '',
            icon: '',
          },
        },
        {
          icon: 'el-icon-s-data',
          name: '推荐产品',
          component: 'recommended-products',
          componentData: {
            titleZh: '推荐商品',
            titleEn: 'Recommended products',
            subTitleZh: '下面这些是您可能会用到的产品',
            subTitleEn: 'These are the products you may use',
            list: [],
          },
        },
        {
          icon: 'el-icon-s-data',
          name: '图标布局',
          component: 'icon-layout',
          componentData: {
            list: [],
            defaultColor: '#0261bc',
          },
        },
        {
          icon: 'el-icon-s-data',
          name: 'tab切换表格',
          component: 'tab-layout',
          componentData: {
            titleZh: '技术规范',
            titleEn: 'Technical Specifications',
            list: [],
          },
        },
        {
          icon: 'el-icon-s-data',
          name: '图文混合排列',
          component: 'mix-graphic-text',
          componentData: {
            list: [],
            titleZh: '',
            titleEn: '',
            sourceZh: '',
            sourceEn: '',
          },
        },
      ],
      renderedComponents: [],
      selectedComponent: {},
      currentIndex: '',
      visible: false,
    }
  },
  computed: {
    isEdit() {
      return this.$route.query.type === 'edit'
    },
    isCopy() {
      return this.$route.query.type === 'copy'
    },
    // 侧边栏表单标题
    drawerTitle() {
      return this.isEdit ? '编辑' : '新增'
    },
    formContent() {
      return [
        {
          $id: 'title',
          $type: 'input',
          label: '页面名称',
          class: 'w-1-1',
          $el: {
            placeholder: '请输入页面名称',
            clearable: true,
            maxlength: 50,
            showWordLimit: true,
          },
          rules: [{ required: true, message: '请输入页面名称', trigger: 'change' }],
        },
        {
          $id: 'description',
          $type: 'input',
          label: '备注',
          class: 'w-1-1',
          $el: {
            placeholder: '请输入备注',
            clearable: true,
            maxlength: 200,
            showWordLimit: true,
          },
        },
      ]
    },
    dragOptions() {
      return {
        animation: 400,
        group: 'component',
        disabled: false,
        ghostClass: 'ghost',
      }
    },
  },
  mounted() {
    ;(this.isEdit || this.isCopy) && this.goPage()
  },
  methods: {
    ...mapActions('tagsView', ['delView']),
    async goPage() {
      try {
        const { code, msg, data } = await this.$axios.$get(
          `${api.solutionContent}/${this.$route.params.id}`
        )

        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        console.log('JSON.parse(data.content)', JSON.parse(data.content))
        this.currentRow = data
        this.renderedComponents = JSON.parse(data.content)
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    onChange() {
      this.selectedComponent = {} // 值发生改变时清空选中
      this.currentIndex = ''
    },
    // 组件设置回调
    itemChange(value) {
      const item = _clonedeep(this.renderedComponents[this.currentIndex])
      item.componentData = _clonedeep(value)
      this.renderedComponents.splice(this.currentIndex, 1, item)
    },
    // 检查拖动元素是否在self-content内容区
    onMoveCallback(evt) {
      return evt.relatedContext.component === this.$refs.dragArea
    },
    // 侧边栏form确认回调
    async onConfirm(data) {
      try {
        const params = {
          ...data,
          content: JSON.stringify(this.renderedComponents),
        }
        // 编辑需要加上id参数
        if (this.isEdit) {
          params.id = this.currentRow.id
        }

        let res = ''

        if (this.isEdit) {
          res = await this.$axios.$put(api.solutionContent, params)
        } else {
          res = await this.$axios.$post(api.solutionContent, params)
        }

        const { code, msg } = res
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }

        this.$message.success('操作成功')
        this.handleBack()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    handleSelect(row, index) {
      this.currentIndex = index
      this.selectedComponent = row
    },
    handleNavigatorChange(val) {
      this.currentNavigator = val
    },
    handleBack() {
      // 清除当前tag
      this.delView({
        name: 'ConfigureSelfPageEdit',
        path: '/configure/self-page/edit/_id',
      })
      this.visible = false
      // 回到列表页，并且刷新页面
      this.$router.push({ path: configureSelfPage })
      this.reload()
    },
    handleDelete() {
      this.renderedComponents.splice(this.currentIndex, 1)
      this.selectedComponent = {}
    },
    handleSave() {
      const { title, description } = this.currentRow

      this.visible = true

      if (this.isEdit) {
        this.$refs.commonForm.updateForm({
          title,
          description,
        })
      }
    },
  },
}
</script>
<style lang="less">
.icon {
  width: 100px; /* 设置SVG的宽度 */
  height: 20px; /* 根据宽度自动调整高度 */
  // fill: #0f0; /* 初始颜色 */
  fill: currentColor;
  color: #0f0;
  transition: fill 0.5s ease; /* 添加颜色过渡效果 */
}
</style>
<style lang="less" scoped>
.self-page {
  width: 100%;
  height: 100%;
  display: flex;
  font-size: 14px;
}

.self-component {
  width: 260px;
  display: flex;
  flex-direction: column;
  border: 1px dashed #e0e4ec;

  h1 {
    font-size: 16px;
    border-bottom: 2px solid #e0e4ec;
    padding: 10px 20px;
  }

  .scroll {
    flex: 1;
    overflow-y: auto;
    flex-wrap: wrap;
    align-items: flex-start;
    font-size: 0;

    .s-row {
      display: inline-block;
      height: 32px;
      line-height: 30px;
      font-size: 12px;
      padding: 0 0 0 8px;
      margin: 15px 0 0 10px;
      width: 115px;
      cursor: move;
      white-space: nowrap;
      text-overflow: ellipsis;
      border-radius: 2px;
      overflow: hidden;
      background: #fafafa;
      border: 1px solid #c1c2c3;

      i {
        color: #409eff;
        margin-right: 4px;
      }
    }
  }
}

.self-detail {
  width: 300px;
  display: flex;
  flex-direction: column;
  border: 1px dashed #e0e4ec;

  h1 {
    font-size: 16px;
    border-bottom: 2px solid #e0e4ec;
    padding: 10px 20px;
  }

  .scroll {
    flex: 1;
    overflow-y: auto;
    flex-wrap: wrap;
    align-items: flex-start;
    font-size: 0;
    padding: 0 10px;

    div {
      & > :deep(.el-form) {
        & > .el-form-item {
          margin-bottom: 5px;

          & > .el-form-item__label {
            padding: 0 0 0;
          }
        }
      }
    }
  }
}

.self-content {
  flex: 1;
  background-color: #f5f5f5;
  overflow: hidden;

  .self-in {
    padding: 20px;
    height: calc(100% - 48px);
  }

  .drag-area {
    overflow-y: auto;
    overflow-x: hidden;
    height: 100%;
    padding-bottom: 20px;

    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &.isMobile {
      border: 10px solid #495060;
      border-radius: 20px;
      width: 398px;
      margin: 0 auto;
      background-color: #fff;
    }

    &.isIpad {
      border: 10px solid #495060;
      border-radius: 20px;
    }

    .operation {
      display: none;
    }

    .active {
      position: relative;
      border: 2px solid #409eff;

      .operation {
        cursor: pointer;
        display: block;
        height: 28px;
        line-height: 28px;
        width: 54px;
        right: 0;
        bottom: 0;
        position: absolute;
        background-color: #409eff;
        color: #fff;
        font-size: 16px;
        text-align: center;
      }
    }
  }

  .header {
    display: flex;
    background-color: #fff;
    height: 46px;
    border: 1px dashed #e0e4ec;
    align-items: center;
    padding: 0 20px;
    margin: 0;

    li {
      list-style: none;
      padding: 0 10px;
      height: 100%;
      line-height: 46px;
      border-bottom: 2px solid #fff;
      cursor: pointer;

      .rotate {
        transform: rotate(90deg);
      }

      &.active {
        border-bottom: 2px solid #409eff;
      }

      &.fr {
        display: flex;
        flex: 1;
        justify-content: flex-end;
        color: #4c6eeb;

        span {
          margin-left: 20px;
        }

        em {
          font-style: normal;
        }
      }
    }
  }
}
</style>
